<template>
    <div class="CreditMgr-container content-wrapper">
        <div class="filter-container">
            <el-form :model="listQuery" :inline="true" ref="filterForm" style="display: inline-block">
                <el-form-item prop="username" class="filter-item">
                    <el-input v-model="listQuery.username" placeholder="用户名" style="width: 200px;"></el-input>
                </el-form-item>
                <el-form-item prop="mobile" class="filter-item">
                    <el-input v-model="listQuery.mobile" placeholder="手机号码" style="width: 200px;"></el-input>
                </el-form-item>
                <el-form-item prop="status">
                    <el-select v-model="listQuery.status" placeholder="状态" clearable style="width: 100px">
                        <el-option
                                v-for="item in statusOptions"
                                :key="item.key"
                                :label="item.label"
                                :value="item.key">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item prop="orderBy" class="filter-item">
                    <el-select v-model="listQuery.orderBy" placeholder="排序" style="width: 150px">
                        <el-option
                                v-for="item in sortOptions"
                                :key="item.key"
                                :label="item.label"
                                :value="item.key">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-button class="filter-item" type="primary" icon="search" @click="handleFilter">搜索</el-button>
                <el-button class="filter-item" type="primary" icon="mars-reset" @click="handleResetFilter">重置</el-button>

                <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="plus" @click="handleCreate()">
                    添加
                </el-button>
            </el-form>
        </div>

        <el-table :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row style="width: 100%">

            <el-table-column label="ID" width="65" align="center">
                <template slot-scope="scope"> {{scope.row.id}} </template>
            </el-table-column>

            <el-table-column label="用户名" width="150px" align="center">
                <template slot-scope="scope"> {{scope.row.username}} </template>
            </el-table-column>

            <el-table-column label="手机号码" width="150px" align="center">
                <template slot-scope="scope"> {{scope.row.mobile}} </template>
            </el-table-column>

            <el-table-column label="扣分原因" width="150px" align="center">
                <template slot-scope="scope"> {{scope.row.deductionReason}} </template>
            </el-table-column>

            <el-table-column label="扣分值" width="150px" align="center">
                <template slot-scope="scope"> {{scope.row.deductionValue}} </template>
            </el-table-column>

            <el-table-column label="扣分日期" width="150px" align="center">
                <template slot-scope="scope"> {{scope.row.deductionDate | parseTime('{y}-{m}-{d}')}} </template>
            </el-table-column>

            <el-table-column label="监控周期" width="250px" align="center">
                <template slot-scope="scope">
                    {{scope.row.monitorDate | parseTime('{y}-{m}-{d}')}}
                    <el-tag type="danger">剩余天数 {{scope.row.surplus}}</el-tag>
                </template>
            </el-table-column>

            <el-table-column label="处理" width="150px" align="center">
                <template slot-scope="scope">
                    <el-button size="small" type="primary" icon="edit" @click="handleDelay(scope.row, scope.row.surplus)">延期</el-button>
                </template>
            </el-table-column>

            <el-table-column label="状态" width="150px" align="center">
                <template slot-scope="scope">
                    <el-tag type="danger" v-if="scope.row.surplus > 0">未完成</el-tag>
                    <el-tag type="success" v-else>已完成</el-tag>
                </template>
            </el-table-column>

            <el-table-column label="备注" min-width="300px" align="center">
                <template slot-scope="scope"> {{scope.row.remarks}} </template>
            </el-table-column>

            <el-table-column label="创建时间" width="150px" align="center">
                <template slot-scope="scope"> {{scope.row.ctime | parseTime('{y}-{m}-{d} {h}:{i}')}} </template>
            </el-table-column>
            <el-table-column label="创建时间" width="150px" align="center">
                <template slot-scope="scope"> {{scope.row.utime | parseTime('{y}-{m}-{d} {h}:{i}')}} </template>
            </el-table-column>

            <el-table-column label="操作" fixed="right" width="180px" align="center">
                <template slot-scope="scope">
                    <el-button size="small" type="primary" icon="edit" @click="handleUpdate(scope.row)">编辑</el-button>

                    <el-button size="small" type="danger" icon="delete" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>

        </el-table>

        <div v-show="!listLoading" class="pagination-container">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="listQuery.page"
                    :page-sizes="[10, 20, 30, 50]"
                    :page-size="listQuery.rows"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>

        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" size="tiny" @close="handleCloseDialog">
            <el-form :model="form" :rules="rules" ref="form" labelPosition="right" labelWidth="80px" style="width: 400px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="form.username"></el-input>
                </el-form-item>
                <el-form-item label="手机号码" prop="mobile">
                    <el-input v-model="form.mobile"></el-input>
                </el-form-item>
                <el-form-item label="扣分原因" prop="deductionReason">
                    <el-input v-model="form.deductionReason"></el-input>
                </el-form-item>
                <el-form-item label="扣分值" prop="deductionValue">
                    <el-input-number :min="0" v-model="form.deductionValue"></el-input-number>
                </el-form-item>
                <el-form-item label="扣分日期" prop="deductionDate">
                    <el-date-picker
                            v-model="form.deductionDate"
                            type="date"
                            placeholder="扣分日期"
                            :editable="false">
                    </el-date-picker>
                </el-form-item>

                <el-form-item label="监控周期">
                    <el-date-picker
                            v-model="form.monitorDate"
                            type="date"
                            placeholder="初始监控周期"
                            :editable="false"
                            :picker-options="pickerOptions">
                    </el-date-picker>
                </el-form-item>

                <el-form-item label="备注">
                    <el-input
                            type="textarea"
                            :autosize="{ minRows: 2, maxRows: 4}"
                            placeholder="请输入内容"
                            v-model="form.remarks">
                    </el-input>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button v-if="dialogStatus == 'create'" type="primary" @click="create">确 定</el-button>
                <el-button v-else="" type="primary" @click="update">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="延期" :visible.sync="dialogDelayFormVisible" size="tiny" @close="handleDelayCloseDialog">
            <el-form :model="formDelay" ref="formDelay" labelPosition="right" labelWidth="80px" style="width: 400px">
                <el-form-item label="天数" prop="delayDate">
                    <el-input-number :min="minDelay" v-model="formDelay.delay"></el-input-number>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogDelayFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="setDelay">确 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
    import fetch from '@/utils/fetch'
    import { created, deleted, updated, fetchObject, fetchList, setDelay } from '@/api/tukuan/credit'
    import {parseTime} from "../../../utils/index";

    const sortOptions = [{label: '按ID升序', key: 'id asc'}, {label: '按ID降序', key: 'id desc'}]
    const statusOptions = [{label: '已完成', key: true}, {label: '未完成', key: false}]

    export default {
        name: 'CreditMgr',
        data() {
            return {
                list: null,
                total: null,
                listLoading: true,
                listQuery: {
                    page: 1,
                    rows: 10,
                    username: undefined,
                    mobile: undefined,
                    status: undefined,
                    orderBy: 'id asc'
                },
                sortOptions,
                statusOptions,
                dialogFormVisible: false,
                dialogDelayFormVisible: false,
                dialogStatus: '',
                textMap: {
                    update: '编辑',
                    create: '创建'
                },
                form: {
                    username: '',
                    mobile: '',
                    deductionReason: '',
                    deductionValue: '',
                    deductionDate: '',
                    monitorDate: '',
                    remarks: ''
                },
                formDelay: {
                    id: '',
                    monitorDate: '',
                    delay: 0
                },
                minDelay: 0,
                rules: {
                    username: [
                        { required: true, message: '请输入用户名', trigger: 'blur' }
                    ],
                    mobile: [
                        { required: true, message: '请输入手机号码', trigger: 'blur' }
                    ]
                },
                pickerOptions: {
                    disabledDate(time) {
                        return time.getTime() < Date.now();
                    },
                    shortcuts: [
                        {
                            text: '一个月',
                            onClick(picker) {
                                const date = new Date();
                                date.setTime(date.getTime() + 3600 * 1000 * 24 * 30);
                                picker.$emit('pick', date);
                            }
                        },
                        {
                            text: '两个月',
                            onClick(picker) {
                                const date = new Date();
                                date.setTime(date.getTime() + 3600 * 1000 * 24 * 60);
                                picker.$emit('pick', date);
                            }
                        }
                    ]
                }
            }
        },
        created() {
            this.getList()
        },
        filters: {
            statusFilter(status) {
                const statusArray = ['正常', '锁定']
                return statusArray[status?--status:'']
            },
            statusTagFilter(status) {
                const statusArray = ['success', 'danger']
                return statusArray[status?--status:'']
            }
        },
        methods: {
            handleDelay(row, surplus) {
                //判断剩余天数是否小于0
                if(surplus >= 0) {
                    this.dialogDelayFormVisible = true
                    //可设置最小天数，最小天数不能小于当前剩余天数
                    this.minDelay = (-(surplus))

                    this.formDelay.id = row.id
                    this.formDelay.monitorDate = row.monitorDate

                } else {
                    this.$notify({
                        title: '提示', message: '已过期，不可设置延期',
                        type: 'error', duration: 2000
                    })
                }
            },
            setDelay() {
                setDelay(this.formDelay).then(response => {
                    if(response.data.status) {
                        this.$notify({
                            title: '成功', message: response.data.message,
                            type: 'success', duration: 2000
                        })
                        this.getList()
                        this.dialogDelayFormVisible = false
                    } else {
                        this.$notify({
                            title: '发生错误', message: response.data.message,
                            type: 'error', duration: 2000
                        })
                    }
                })
            },
            getList() {
                this.listLoading = true
                fetchList(this.listQuery).then(response => {
                    this.list = response.data.list
                    this.total = response.data.total
                    this.listLoading = false
                }).catch((error)=>{
                    console.log(error)
                    this.listLoading = false
                })
            },
            handleSizeChange(val) {
                this.listQuery.rows = val
                this.getList()
            },
            handleCurrentChange(val) {
                this.listQuery.page = val
                this.getList()
            },
            handleCloseDialog() {
                this.resetForm()
            },
            handleDelayCloseDialog() {
                this.resetFormDelay()
            },
            handleFilter() {
                this.listQuery.page = 1
                this.getList()
            },
            handleResetFilter() {
                this.$refs.filterForm.resetFields()
                this.getList()
            },
            handleCreate() {
                this.dialogStatus = 'create'
                this.dialogFormVisible = true
            },
            handleUpdate(row) {
                this.dialogStatus = 'update'

                fetchObject(row.id).then(response => {
                    this.dialogFormVisible = true
                    this.form = Object.assign({}, response.data)
                })
            },
            handleDelete(row) {
                this.$confirm('确定要删除？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    deleted(row.id).then(response => {
                        if(response.data.status) {
                            this.$notify({
                                title: '成功', message: response.data.message,
                                type: 'success', duration: 2000
                            })
                            this.getList()
                        } else {
                            this.$notify({
                                title: '发生错误', message: response.data.message,
                                type: 'error', duration: 2000
                            })
                        }
                    })
                }).catch(() => {
                    this.$message({ type: 'info', message: '已取消删除' })
                })
            },
            create() {

                this.$refs['form'].validate((valid) => {
                    if(valid) {
                        this.form.deductionDate = parseTime(this.form.deductionDate, '{y}-{m}-{d} {h}:{i}:{s}')
                        this.form.monitorDate = parseTime(this.form.monitorDate, '{y}-{m}-{d} {h}:{i}:{s}')
                        created(this.form).then(response => {
                            if(response.data.status) {
                                this.$notify({
                                    title: '成功', message: response.data.message,
                                    type: 'success', duration: 2000
                                })
                                this.getList()
                            } else {
                                this.$notify({
                                    title: '操作失败', message: response.data.message,
                                    type: 'error', duration: 2000
                                })
                            }
                            this.dialogFormVisible = false
                        })
                    }
                })

            },
            update() {
                this.$refs['form'].validate((valid) => {
                    if(valid) {
                        this.form.deductionDate = parseTime(this.form.deductionDate, '{y}-{m}-{d} {h}:{i}:{s}')
                        this.form.monitorDate = parseTime(this.form.monitorDate, '{y}-{m}-{d} {h}:{i}:{s}')
                        updated(this.form).then(response => {
                            if(response.data.status) {
                                this.$notify({
                                    title: '成功', message: response.data.message,
                                    type: 'success', duration: 2000
                                })
                                this.getList()
                            } else {
                                this.$notify({
                                    title: '发生错误', message: response.data.message,
                                    type: 'error', duration: 2000
                                })
                            }
                            this.dialogFormVisible = false
                        })
                    }
                })
            },
            resetForm() {
                this.$refs['form'].resetFields()
                this.form = {
                    username: '',
                    mobile: '',
                    deductionReason: '',
                    deductionValue: '',
                    deductionDate: '',
                    monitorDate: '',
                    deductionReason: '',
                    remarks: ''
                }
            },
            resetFormDelay() {
                this.$refs['formDelay'].resetFields()
                this.formDelay = {
                    id: '',
                    monitorDate: '',
                    delay: 0
                }
            }
        }
    }
</script>

<!-- 局部样式 -->
<style rel="stylesheet/scss" lang="scss" scoped>

</style>